<!--
 * @Author: ShiJunJie
 * @Date: 2021-11-02 14:09:53
 * @LastEditors  : ShiJunJie
 * @LastEditTime : 2022-04-18 16:04:36
 * @Descripttion: 
-->
<!-- 
  表格跨行颜色
  :row-class-name="(_record, index) => (index % 2 === 1 ? 'table-striped' : null)"
-->
<template>
  <section class="table-view">
    <div class="tableTitle" v-if="useSlots().title">
      <slot name="title"></slot>
      <BaseTableShowRoll ref="BaseTableShowRollDom" :options="newColumn" style="float: right" />
    </div>
    <a-table
      v-if="BaseTableShowRollDom?.columns"
      class="ant-table-striped"
      size="small"
      :loading="loading"
      :columns="BaseTableShowRollDom?.columns"
      :dataSource="newDataScourde"
      :pagination="false"
      :scroll="newScroll"
      :rowSelection="rowSelection"
      :bordered="bordered"
      rowKey="id"
      @resizeColumn="handleResizeColumn"
      @change="onChange"
    >
      <template #headerCell="{ column }">
        <template v-if="column.ellipsis === true">
          <a-tooltip color="#fff" placement="topLeft">
            <template #title>
              <span style="color: #7b8ba1">{{ column.title }}</span>
            </template>
            <div class="cell-ellipsis">{{ column.title }}</div>
          </a-tooltip>
        </template>
        <template v-else>
          {{ column.title }}
        </template>
      </template>

      <template #bodyCell="{ column, record }">
        <!-- 包裹方法 -->
        <div @click.stop="column.fun ? column.fun(record) : ''" :style="[column.fun ? 'cursor:pointer' : '']">
          <template v-if="column.key === 'operation'">
            <!-- 操作栏 -->
            <template v-if="column.funs && column.funs.length > 0">
              <template v-for="(e, i) in column.funs" :key="i">
                <template v-if="e.show ? e.show(record) : true">
                  <template v-if="e.label === 'PDF' || e.label === 'EXCEL'">
                    <a-button type="link" @click="e.fun(record)" :disabled="e.disabled ?? false">
                      <Iconfont class="pdf-excel" :name="e.label === 'PDF' ? 'icon-pdf' : 'icon-PC-Excel'" />
                    </a-button>
                  </template>
                  <template v-else>
                    <a-popconfirm
                      v-if="!!e.popconfirm || ['删除'].indexOf(e.label) !== -1"
                      placement="topRight"
                      :title="e?.popconfirm?.title ?? '确认执行此操作吗？'"
                      :ok-text="e?.popconfirm?.ok ?? '确认'"
                      :cancel-text="e?.popconfirm?.cancel ?? '取消'"
                      @confirm="e?.fun(record)"
                      @cancel="() => {}"
                    >
                      <a-button
                        type="link"
                        :danger="['删除'].indexOf(e.label) !== -1 || e.danger"
                        :disabled="e.disabled ?? false"
                      >
                        <span>{{ e.label }}</span>
                      </a-button>
                    </a-popconfirm>
                    <a-button
                      v-else
                      type="link"
                      @click="e.fun(record)"
                      :danger="['删除'].indexOf(e.label) !== -1 || e.danger"
                      :disabled="e.disabled ?? false"
                    >
                      <span>{{ e.label }}</span>
                    </a-button>
                  </template>
                </template>
              </template>
            </template>
          </template>

          <template v-else-if="column.type === 'status'">
            <!-- 状态对照  -->
            <div class="statusPoint">
              <i
                class="point"
                v-if="column.typeData[record[column.key]]?.color"
                :style="{
                  backgroundColor: column.typeData[record[column.key]]?.color,
                }"
              ></i>
              <span>{{ column.typeData[record[column.key]]?.label }}</span>
            </div>
          </template>

          <template v-else-if="column.type === 'swatches'">
            <!-- 色板  -->
            <div :style="`height: 23px;background-color:${getTagColor(record[column.key])}`"></div>
          </template>

          <template v-else-if="column.type === 'icon'">
            <!-- 图标  -->
            <a-space>
              <Iconfont :name="record[column.key]" />
              <span>{{ record[column.key] }}</span>
            </a-space>
          </template>

          <template v-else-if="['tags', 'tagsCard'].indexOf(column.type) !== -1">
            <!-- 标签组  -->
            <a-tooltip color="#fefefe" placement="bottomLeft" v-if="record[column.key].length > 0">
              <template #title>
                <div class="cards" :class="[column.type === 'tagsCard' ? 'tagsCard' : '']">
                  <template v-for="(e, i) in record[column.key]" :key="i">
                    <span class="card" :style="{ color: e.color }" v-if="e['label']">
                      {{ e.label }}
                      <Iconfont
                        v-if="column.type === 'tags'"
                        name="icon-close"
                        @click.stop="column.tagsFun ? column.tagsFun({ codeId: record.id, tagId: e.id }) : ''"
                      />
                    </span>
                  </template>
                </div>
              </template>
              <div class="cards noWarp" :class="[column.type === 'tagsCard' ? 'tagsCard' : '']">
                <template v-for="(e, i) in record[column.key]" :key="i">
                  <span class="card" :style="{ color: e.color }" v-if="e['label']">
                    {{ e.label }}
                    <Iconfont
                      v-if="column.type === 'tags'"
                      name="icon-close"
                      @click.stop="column.tagsFun ? column.tagsFun({ codeId: record.id, tagId: e.id }) : ''"
                    />
                  </span>
                </template>
              </div>
            </a-tooltip>
            <template v-else>-</template>
          </template>

          <template v-else-if="column.type === 'progress'">
            <!-- 进度条  -->
            <a-row style="flex" v-if="record[column.key]" :gutter="[0, 8]">
              <a-col flex="auto">
                <a-progress
                  :percent="parseInt(record[column.key])"
                  size="small"
                  style="cursor: pointer"
                  :showInfo="false"
                />
              </a-col>
              <a-col style="width: 55px; text-align: right"
                >{{ record[column.key] === 'NaN' ? '0.0' : record[column.key] }}%</a-col
              >
            </a-row>
            <template v-else>-</template>
          </template>

          <template v-else-if="column?.format">
            <!-- 自动时间格式化 -->
            {{ dayjsFormat(record[column.key], column?.format) }}
          </template>

          <template v-else-if="column.ellipsis === true">
            <!-- 单行显示  -->
            <a-tooltip
              color="#fff"
              placement="bottomLeft"
              v-if="record[column.key] && record[column.key] !== 'Invalid Date'"
            >
              <template #title>
                <span style="color: #7b8ba1">{{ record[column.key] }}</span>
              </template>
              <div class="cell-ellipsis">
                <Iconfont :name="column.icon && column.icon(record)" />
                {{ record[column.key] || '-' }}
              </div>
            </a-tooltip>
            <template v-else>-</template>
          </template>

          <template v-else>
            <!-- 默认 -->
            {{ record[column.key] === 'Invalid Date' ? '-' : record[column.key] }}
          </template>
        </div>
      </template>
    </a-table>

    <BaseTablePage v-show="!hidePage" :total="total" :page="page" :size="size" @pageChange="pageChange" />
  </section>
</template>

<script setup>
import { computed, onMounted, watch, onUnmounted, reactive, toRaw, readonly, unref, useSlots } from 'vue'
import { _debounce as debounce, getTagColor } from '@/utils/util'
import dayjs from 'dayjs'

// import BaseTableShowRoll from './BaseTableShowRoll';

const BaseTableShowRollDom = ref(null)

const props = defineProps({
  total: { type: Number, default: 0 },
  page: { type: Number, default: 1 },
  loading: Boolean,
  size: { type: Number, default: 10 },
  columns: { type: Array, default: [] },
  dataSource: { type: Array, default: [] },
  rowSelect: { type: Boolean, default: false },
  hidePage: { type: Boolean, default: false },
  bordered: { type: Boolean, default: false },
  selectData: { type: Array, default: [] },
})
let selectedRowKeys = ref([])
watch(
  () => props.selectData,
  (a, b) => {
    selectedRowKeys.value = toRaw(a)
    // console.log(toRaw(a), toRaw(b))
  }
)

const emit = defineEmits(['page', 'rowSelectData', 'update:selectData', 'change'])

const rowSelection = computed(() => {
  if (props.rowSelect === true) {
    return {
      preserveSelectedRowKeys: selectedRowKeys.value,
      selectedRowKeys: selectedRowKeys.value,
      onChange: (selectedRowKeys, selectedRows) => {
        emit('rowSelectData', selectedRowKeys)
        emit('update:selectData', selectedRowKeys)
        console.log(`selectedRowKeys: ${selectedRowKeys}`, '\nselectedRows: ', selectedRows)
      },
      getCheckboxProps: record => ({
        // disabled: record.name === "",
        name: record.name,
      }),
    }
  } else if (props.rowSelect !== false) {
    return props.rowSelect
  } else {
    return null
  }
})

const pageChange = (page, size) => {
  emit('pageChange', page, size)
}

let newScroll = reactive({ x: 'max-content', y: 200 })
// let newScroll = reactive({ y: 200 })

const newColumn = computed(() => {
  const columns = reactive(
    props.columns && props.columns.length > 0
      ? [
          ...Array.from(props.columns, (e, i) => {
            const columns_e = {
              key: e.dataIndex,
              // resizable: e.dataIndex !== 'operation' && !!e.width,
              sorter: e.sorter ? true : false,
              fixed: e.dataIndex === 'operation' ? 'right' : false,
              ...e,
              width: e.width || e.title.length * 14 + 40,
              minWidth: e.width || e.title.length * 14 + 40,
            }

            newScroll.x += columns_e.width || 0
            if (props.columns.length < 5 && props.columns.length - 2 === i) {
              // if (i === 0) {
              // columns.width = null;
            }
            // console.log(newScroll, columns_e.width, columns_e, e.title.length * 14 + 40);
            return columns_e
          }),
        ]
      : [
          { title: 'name', key: 'name', dataIndex: 'name' },
          { title: 'value', key: 'value', dataIndex: 'value' },
          { title: 'value2', key: 'value2', dataIndex: 'value2' },
          {
            title: '操作',
            key: 'operation',
            fixed: 'right',
            align: 'center',
            funs: [{ label: '修改', fun: e => console.log(e) }],
          },
        ]
  )
  // 向数组倒数第二的位置添加一个空元素
  return columns
})

const newDataScourde = computed(() => {
  return props.dataSource // && Array.from(props.dataSource, e => ({ key: e.id, ...e }))
})
const dayjsFormat = (date = '', format) => {
  format = format === true ? 'YYYY-MM-DD HH:mm:ss' : format
  const resData = dayjs(date).format(format)
  // console.log(date, format, resData)
  if (resData !== 'Invalid Date') {
    return resData
  } else {
    return '-'
  }
}

const setNewScroll_y = () => {
  const overflow = !props.hidePage ? 92 : 35
  const y =
    document.getElementsByTagName('body')[0].offsetHeight -
    document.getElementsByClassName('ant-table-wrapper')[0].offsetTop -
    document.getElementsByClassName('ant-table-body')[0].offsetTop -
    overflow
  newScroll.y = y
  console.log(
    y,
    document.getElementsByTagName('body')[0].offsetHeight,
    document.getElementsByClassName('ant-table-body')[0].offsetTop
  )
}
watch(
  () => props.dataSource,
  () => setNewScroll_y()
)
onMounted(() => {
  window.onresize = debounce(setNewScroll_y)
})
onUnmounted(() => {
  console.log('表格自适应组件方法销毁')
  window.onresize = null
})

const handleResizeColumn = (w, col) => {
  console.log(w, col)
  col.width = w
}
const onChange = (pagination, filters, sorter, extra) => {
  emit('change', pagination, filters, sorter, extra)
  // console.log('params', pagination, filters, sorter, extra)
}
defineExpose({ setNewScroll_y: debounce(setNewScroll_y) })
</script>

<style lang="less" scoped>
// .ant-table-striped :deep(.table-striped) td {
//   // background-color: #fafafa;
// }
:deep(.ant-table) tr {
  td {
    transition: all 0.3s cubic-bezier(0.4, 0.8, 0.4, 1);
    animation: all 0.3s cubic-bezier(0.4, 0.8, 0.4, 1);
    -moz-transition: all 0.3s cubic-bezier(0.4, 0.8, 0.4, 1);
    -webkit-transition: all 0.3s cubic-bezier(0.4, 0.8, 0.4, 1);
    -o-transition: all 0.3s cubic-bezier(0.4, 0.8, 0.4, 1);

    // opacity: 0.7;
    color: #777;

    &.ant-table-cell-fix-right {
      // opacity: 1;
    }
  }

  &:hover td {
    color: #333;
    // opacity: 1;
  }
}
// :deep(.ant-table-wrapper),
.base-table-page {
  box-shadow: 0px -4px 7px 0px #e0e0e09e;
  padding: 20px 20px 0 20px;
  position: relative;
  z-index: 100;
}

.table-view {
  width: 100%;
  padding: 20px 0px;
  overflow: hidden;

  .tableTitle {
    margin-bottom: 12px;
  }

  .ant-btn {
    padding: 0;
    height: auto;

    + .ant-btn {
      margin-left: 15px;
    }
  }

  .cell-ellipsis {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    word-break: keep-all;
  }

  .statusPoint {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;

    .point {
      width: 6px;
      height: 6px;
      margin-right: 5px;
      background: #f00;
      border-radius: 100%;
    }
  }
}

.cards {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
  gap: 8px;

  &.noWarp {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    word-break: keep-all;
    display: block;

    .card {
      margin-right: 8px;
    }
  }

  .card {
    border: 1px solid transparent;
    border-radius: 2px;
    line-height: 100%;
    padding: 3px 5px;
    display: inline-flex;
    align-items: center;
    gap: 4px;
    padding-right: 19px;

    .svg-icon {
      display: none;
      font-size: 10px;
    }

    &:hover {
      padding-right: 5px;
      border: 1px solid;

      .svg-icon {
        cursor: pointer;
        display: block;
      }
    }
  }

  &.tagsCard {
    .card {
      padding-right: 5px;
      margin-right: 0px;

      &:hover {
        border: 1px solid transparent;
      }
    }
  }
}

.pdf-excel {
  font-size: 20px;
}
</style>
